# -*- coding: utf-8 -*-
"""
Created on Tue Apr 11 10:06:01 2023

@author: Sandra
"""
import subprocess
import pandas as pd
import os
from read_xlsx_sheet1 import read_execle,Coating_Name,Coating_Name_row_element
from read_xlsx_sheet2 import replace_text_in_file_sheet2_Define,replace_text_in_file_sheet2_Emitter
from read_xlsx_sheet3 import replace_text_in_file_sheet3_Commands
import re
import math
import numpy as np
from tqdm import tqdm

def update_par_file(main_file, out_file, spectrum_string,execel_file,project_file_path):

    #主要是针对表格内容和setfos 内容不一致时，把setfos没有的确实的内容补全行，在对其就行操作。
    with open(main_file, "r") as file:
        file_lines = file.readlines()


    last_match_index = -1
    list1 = Coating_Name(execel_file,1)
    # 处理每个 list3

    for list3 in list1:
        # pattern = "Layer "+str(list3).strip()+" "+".*"
        pattern = "Layer\s*.*?\s*" + re.escape(str(list3).strip()) + "\s*.*"
        default_str = "Layer " + str(list3).strip() + " "+"\n"

        # 查找匹配项
        matches = [line for line in file_lines if re.search(pattern, line, re.MULTILINE)]

        # 如果没有找到匹配项，添加 default_str
        if not matches:
            for i, line in enumerate(file_lines):
                if line.startswith("Layer "):
                    # 在最近的 Layer 行之后插入 default_str
                    file_lines.insert(i + 1, default_str)
                    break  # 插入后退出循环
        else:
            # 更新最后一个匹配的行索引
            last_match_index = matches[-1]
        # 将修改后的内容写回文件
    with open(main_file, "w") as file:
        file.writelines(file_lines)
    # file.close()



    # 打开原始par文件进行读取
    with open(main_file, "r") as StartPar:
        StartPar_text = StartPar.read()


    #列名 #list Air2 PAS IL2 IL1 SiON-i4 ....
    # string3=''
    #存放替换的字符串
    list4=[]#存放value
    dict_coatingname = {}
    list1 = Coating_Name(execel_file,1)
    print(list1)
    list2 = Coating_Name_row_element(execel_file,1)
    total_coatings = len(list1) * len(list2)
    with tqdm(total=total_coatings, desc="处理膜层信息") as pbar:
        for i in range(0, len(list1)):
            for j in range(0, len(list2)):
                result = read_execle(execel_file, list1[i], list2[j],1)
                dict_coatingname[list2[j]] = result
                pbar.update(1)


            #天大的坑，循环控制错了，放在内层了
            refractive_index_curve = dict_coatingname.get('折射率曲线')
            # print(type(refractive_index_curve))
            if refractive_index_curve is None:  # 如果折射率曲线为空字符串，跳过当前行
                continue
            coating_name = dict_coatingname.get('膜层名称')
            thickness = dict_coatingname.get('厚度')
            unit = dict_coatingname.get('单位')
            coating_property = dict_coatingname.get('膜层特性')

            is_disabled = dict_coatingname.get('是否勾选')
            layer_str = f"Layer " + (f"{is_disabled} " if is_disabled else "") + coating_name

            # if thickness and unit:
            layer_str += f" {thickness} {unit} n "

            if refractive_index_curve is not None:  # 如果不为空
                try:
                    # 尝试将 refractive_index_curve 转换为浮点数
                    float_value = float(refractive_index_curve)
                    # 如果转换成功，拼接数字
                    layer_str += f" {float_value}"
                except ValueError:
                    # 如果转换失败（即 refractive_index_curve 不是数字），则处理为文件名
                    # 拼接字符串，表示这是一个文件名
                    #先拼接第一个字符串
                    layer_str += f' File "{spectrum_string}/{refractive_index_curve.split()[0]}.txt"'
            

            if coating_property:
                layer_str += f" {coating_property}"
            list4.append(layer_str)
            # print(layer_str)  # 使用 strip() 移除字符串两端的空白字符

    with open(main_file, 'r') as file:
        lines = file.readlines()

    start_tag='Structure'
    end_tag='Define'

    start_extract = False
    modified_lines = []
    #模糊查询end_tag
    end_tag_pattern = re.compile(end_tag)

    for line in lines:
        if start_tag in line:  # 如果找到 start_tag，包括这一行
            modified_lines.append(line)
            start_extract = True
            # 添加新内容，每个元素占据一行
            for content in list4:
                modified_lines.append(content + '\n')
            continue
        elif start_extract:
            if end_tag_pattern.search(line):  # 如果找到 end_tag，跳过这一行
                modified_lines.append(line)
                start_extract = False
                continue  # 跳过 end_tag 所在的行
            else:
                # 跳过旧内容，因为我们已经用新内容替换了
                continue
        else:
            modified_lines.append(line)  # 复制旧内容
    string3=f"{project_file_path}/{out_file}"
    with open(string3, 'w') as file:
        file.writelines(modified_lines)

# PL_files = []


# write simulation files
# PL_path ='C:/Users/admin/Desktop/03_simulation_example/00 Structure/00 NK'
# runsim = False # set to True if you also want to run the simulation
# setfos_dir = "C:/Setfos 5.2 (x64)/Setfos 5.2 (x64)/"
# executable = setfos_dir + "setfos-kernel.exe"


